package top.lightHearted.socket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * WebSocketHandler class
 *
 * @author gpf
 * @date 2018/03/23
 */
@Component
public class WebRTCHandler extends TextWebSocketHandler {

    static Map<String, WebSocketSession> USER_ID_TO_SESSION = new HashMap<>();

    @Autowired
    private JmsTemplate jmsTemplate;

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        USER_ID_TO_SESSION.put(session.getId(), session);
        sendMessageToClientWithoutSelf(message, session.getId());
    }

    private void sendMessageToClientWithoutSelf(TextMessage message, String selfId)  throws Exception {
        for(WebSocketSession socketSession: USER_ID_TO_SESSION.values()){
            System.out.println(socketSession.getId() + "====================" + socketSession.isOpen());
            if(socketSession.isOpen()){
                if(!socketSession.getId().equals(selfId)){
                    socketSession.sendMessage(message);
                    System.out.println("++++++++++++++++++++++send message to client++++++++++++++++++++++");
                }
            }else{
                USER_ID_TO_SESSION.remove(socketSession.getId());
            }
        }
    }

}
